<template>
  <div class="padding-16">
    <a-card class="general-card" title="文章分类">
      <a-form
        ref="refSearchForm"
        :model="searchForm"
        auto-label-width
      >
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="name" label="分类名称">
              <a-input v-model="searchForm.name" placeholder="请输入分类名称" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="status" label="可见性">
              <a-select v-model="searchForm.status" :options="visibleOptions" placeholder="全部" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-space :size="16">
              <a-button type="primary" @click="fetchTableData()">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="$refs.refSearchForm.resetFields()">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-divider style="margin-top: 0" />
      <a-space style="margin-bottom: 16px">
        <a-button size="small" type="primary" @click="handleEdit()">
          <template #icon>
            <icon-plus />
          </template>
          新增
        </a-button>
      </a-space>

      <a-table
        bordered
        row-key="id"
        :data="tableData"
        default-expand-all-rows
        :loading="loading"
        :pagination="false">

        <template #columns>
          <a-table-column title="栏目名称" data-index="name"></a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <DictBadge :options="visibleOptions" :value="record.status"/>
            </template>
          </a-table-column>
          <a-table-column title="排序" data-index="sort"></a-table-column>
<!--          <a-table-column title="备注" data-index="remark"></a-table-column>-->
          <a-table-column title="创建时间" data-index="create_time"></a-table-column>
          <a-table-column title="操作" :width="160">
            <template #cell="{ record }">
              <a-button type="text" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                <a-button type="text" status="danger">删除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    <!-- 分类弹窗 -->
    <a-modal title="文章分类" v-model:visible="dialogVisible" :footer="false">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        auto-label-width
        @submit="handleSubmit"
      >
        <a-form-item label="分类名称" field="name">
          <a-input v-model="formState.name" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="上级分类" field="parent_id">
          <a-tree-select
            v-model="formState.parent_id"
            node-key="id"
            :data="categoryOptions"
            :field-names="fieldNames"
            placeholder="请选择上级分类"
          />
        </a-form-item>
        <a-form-item label="分类图片" field="image_id">
          <a-input v-model="formState.image_id" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="是否可见" field="status">
          <a-radio-group v-model="formState.status">
            <a-radio v-for="item in visibleOptions" :key="item.value" :value="item.value">{{ item.label }}</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="排序" field="sort">
          <a-input-number v-model="formState.sort" :min="0" :max="9999" />
        </a-form-item>
        <a-form-item label="简介" field="description">
          <a-textarea
            v-model="formState.description"
            placeholder="简介"
            auto-size
            :maxlength="200"
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <div class="form-footer">
          <a-button key="submit" html-type="submit" type="primary" :loading="loading">确 定</a-button>
          <a-button class="ml-24" @click="handleCancel">取 消</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, computed, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import get from "lodash/get";
import useLoading from "@/hooks/loading.ts";
import { categoryTreeList, categoryDelete, categoryCreate, categoryUpdate } from "@/api/content/article.ts";
import { visibleOptions } from "@/enums/status.ts";

/**
 * 树选择框
 */
const fieldNames = {
  title: "name",
  key: "id",
  children: "children"
};

const tableData = ref([]);
const categoryOptions = ref([]);

const searchForm = reactive({
  name: "",
  status: ""
});

const { loading, setLoading } = useLoading(true);

async function fetchTableData() {
  setLoading(true);
  try {
    const { data } = await categoryTreeList(searchForm);
    tableData.value = data || [];
    if (!searchForm.name && !searchForm.status) {
      categoryOptions.value = [{ name: "一级分类", id: 0 }].concat(data || []);
    }
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
}

onMounted(() => {
  fetchTableData();
});

async function handleDelete(rowData) {
  if (!rowData.id) return;
  setLoading(true);
  try {
    const { msg } = await categoryDelete(rowData);
    Message.success(msg || "删除成功！");
    await fetchTableData();
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
}

// 创建编辑弹窗
const dialogVisible = ref(false);
const formRef = ref();
const formState = reactive({
  id: "",
  name: "",
  parent_id: undefined,
  description: "",
  image_id: "",
  status: 1,
  sort: 10
});

const handleEdit = (rowData: any) => {
  dialogVisible.value = true;
  if (rowData?.id) {
    formState.id = rowData.id;
    formState.name = rowData.name;
    formState.parent_id = rowData.parent_id
    formState.description = rowData.description;
    formState.image_id = rowData.image_id;
    formState.status = rowData.status;
    formState.sort = rowData.sort;
  }
};

const formRules = reactive({
  name: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
  status: [{ required: true, message: "可见状态不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }]
});

const handleCancel = () => {
  dialogVisible.value = false;
  formRef.value.resetFields();
};

const handleSubmit = async ({ values, errors }) => {
  console.log("values:", values, "\nerrors:", errors);
  if (!errors) {
    const params = {
      ...formState
    };

    setLoading(true);
    try {

      if (params.id) {
        await categoryUpdate(params);
      } else {
        await categoryCreate(params);
      }

      Message.success("保存成功！");
      await fetchTableData();
      handleCancel();
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  }
};
</script>

<style scoped lang="less">
.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
